package com.mall.service;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mall.dao.mapper.UserMapper;
import com.mall.exception.MyException;
import com.mall.model.User;
import com.mall.model.UserExample;
import com.mall.model.UserExample.Criteria;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	
	public User save(User user) throws Exception {
		if(this.getUser(user.getUsername())!=null){
			throw new MyException("该用户名已被注册!");
		}
		Date date = new Date();
		user.setCdate(date);
		user.setLdate(date);
		user.setUdate(date);
		user.setImg("defImg.png");
		int insert = userMapper.insert(user);
		if (insert == 0) {
			throw new Exception();
		}

		return this.getUser(user.getUsername());
	}
	/**
	 * 是否存在用户
	 *
	 *@dagewang 2017年8月24日
	 */
	public User getUser(String username) {
		UserExample ue = new UserExample();
		ue.createCriteria().andUsernameEqualTo(username);
		List<User> selectByExample = userMapper.selectByExample(ue);
		if(selectByExample.size()!=0){
			return selectByExample.get(0);
		}
			return null;
	}
	/**
	 * 根据id获取user
	 *
	 *@dagewang 2017年8月24日
	 */
	public User getUser(Integer id)throws Exception {
		
			return userMapper.selectByPrimaryKey(id);
	}
	/**
	 * 根据账号密码获取user
	 *
	 *@dagewang 2017年8月24日
	 */
	public User get(String username, String password) throws Exception{
		UserExample ue = new UserExample();
		Criteria c = ue.createCriteria();
		c.andUsernameEqualTo(username);
		c.andPasswordEqualTo(password);
		List<User> list=null;
		try {
			list = userMapper.selectByExample(ue);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(list.size()==0){
			return null;
		}
		return list.get(0);
	}
	public UserMapper getUserMapper() {
		return userMapper;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}
	/**
	 * 上传用户头像
	 * @param id 
	 *
	 *@dagewang 2017年9月19日
	 */
	public String uploadImg(MultipartFile m, HttpServletRequest hsr,String path, Integer id)throws Exception {
		String root=hsr.getServletContext().getRealPath(path);
		String originalFilename = m.getOriginalFilename();
		String newImgName=id+"-"+UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
		File file=new File(root+newImgName);
		m.transferTo(file);
		return newImgName;
	}
	/**
	 * 更新用户信息
	 *
	 *@dagewang 2017年9月19日
	 */
	public int update(User user) {
		user.setUdate(new Date());
		return userMapper.updateByPrimaryKeySelective(user);
	}
	

}
